package com.lkx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkx.common.R;
import com.lkx.dto.DishDto;
import com.lkx.dto.SetmealDto;
import com.lkx.pojo.Category;
import com.lkx.pojo.Dish;
import com.lkx.pojo.Setmeal;
import com.lkx.pojo.SetmealDish;
import com.lkx.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName: com.lkx.controller.SetMealController
 * @author: likaixin
 * @create: 2022年11月24日 16:03
 * @desc: 套餐管理
 */
@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetMealController {

    @Autowired
    private SetMealService setMealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishDtoService dishDtoService;

    @Cacheable(value = "show",key = "#id")
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> showSetMeal(@PathVariable Long id){
        List<DishDto> copies = dishDtoService.copies(id);
        return R.success(copies);


    }
    /**
     * @Date:  2022-11-24
     * @Time:  16:55
     * @Param: [setmealDto]
     * @return: com.lkx.common.R<java.lang.String>
     * @desc: 新增套餐
     **/
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("已接收前端发来的json，保存到setmealDto实体类中{}",setmealDto);
        setMealService.saveWithDish(setmealDto);
        return R.success("ok");
    }
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={},pageNum={},pageSize={}",page,pageSize,name);
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(Objects.nonNull(name),Setmeal::getName,name).orderByDesc(Setmeal::getUpdateTime);
        setMealService.page(pageInfo,lqw);
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (Objects.nonNull(category)) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
            //根据分类的id
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }
    /**
     * @Date:  2022-11-24
     * @Time:  19:35
     * @Param: [ids]
     * @return: java.lang.String
     * @desc: 删除套餐
     **/
    @DeleteMapping()
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(Long[] ids){
        log.info("ids:{}",ids);
        setMealService.removeWithDish(ids);
        return R.success("ok");
    }
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> modifyStatus(@PathVariable Integer status,Long[] ids){
        UpdateWrapper<Setmeal> wrapper = new UpdateWrapper<>();
        wrapper.in("id",ids).set("status",status);
        List<Setmeal> setmealList = setMealService.listByIds(Arrays.stream(ids).collect(Collectors.toList()));


        boolean flag = setMealService.update(wrapper);
        if (flag){
            return R.success("修改状态成功！");
        }
        return R.error("修改失败");
    }
    @GetMapping("{id}")
    public R<Setmeal> echo(@PathVariable Long id){
        log.info("接收到id：{}",id);
        SetmealDto dto = setMealService.getByIdWithFlavor(id);


        return R.success(dto);
    }
    //修改套餐
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PutMapping
    public R<String> update(@RequestBody SetmealDto dto){

        log.info("接收到：{}",dto);
        setMealService.updateSetMeal(dto);
        return R.success("修改套餐成功");
    }
    /**
     * @Date:  2022-11-26
     * @Time:  17:44
     * @Param: [setmeal]
     * @return: com.lkx.common.R<java.util.List<com.lkx.pojo.Setmeal>>
     * @desc: 根据条件查询套餐数据
     **/
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(setmeal.getCategoryId()),Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(Objects.nonNull(setmeal.getStatus()),Setmeal::getStatus,1);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list= setMealService.list(queryWrapper);
        return R.success(list);
    }
}
